<template>
  <Card>
    <Form id="searchForm" ref="searchForm" :label-width="90" :model="searchForm" inline>
      <!-- <Form-item label="车辆线路：" prop="line">
        <Select clearable placeholder="选择线路" style="width:200px;" v-model="searchForm.line">
          <Option value="-1">全部</Option>
          <Option :key="item.line" :value="item.line" v-for="item in lines">{{ item.line }}</Option>
        </Select>
      </Form-item> -->
      <Form-item label="车牌号：" prop="license_plate_num">
        <Input
          v-model="searchForm.license_plate_num"
          clearable
          placeholder="支持模糊搜索"
          style="width: 200px"
          type="text"
        />
      </Form-item>
      <Form-item label="日期范围：" prop="date">
        <DatePicker
          v-model="searchForm.date"
          format="yyyy-MM"
          placeholder="请选择月份"
          placement="bottom-start"
          style="width: 200px"
          type="month"
          @on-change="dateChange"
        ></DatePicker>
      </Form-item>
      <Form-item style="margin-left:-90px;">
        <Button icon="md-search" type="primary" @click="getDataList()">搜索</Button>
        <Button @click="handleReset()">重置</Button>
      </Form-item>
    </Form>
    <Row id="generate">
      <Button
        :disabled="exportBtnDisable"
        icon="md-cloud-download"
        style="float: left;margin-top: 2px;"
        type="primary"
        @click="exportTaskRank"
      >导出
      </Button>
      <Button style="float: left;margin-left: 20px;margin-top: 2px;" type="success" @click="saveEvent">保存</Button>
      <Alert v-show="showAlert" style="float: left;margin-left: 20px;" type="error">{{ date_text }}</Alert>
      <Form ref="dataForm" :label-width="90" :model="dataForm" inline>
        <Form-item label="日期范围：" prop="date">
          <DatePicker
            v-model="dataForm.date"
            placeholder="请选择月份"
            placement="bottom-start"
            style="width: 200px"
            type="month"
            @change="dateChange('data')"
          ></DatePicker>
        </Form-item>
        <Button :loading="dataLoading" icon="md-search" type="primary" @click="createData()">生成排名</Button>
      </Form>
    </Row>
    <vxe-table
      id="salaryTable"
      ref="xTable"
      :align="allAlign"
      :data="data"
      :edit-config="{trigger: 'click', mode: 'cell', showStatus: true}"
      :height="height"
      :loading="listLoading"
      :span-method="handleSpan"
      border
      highlight-hover-row
      keep-source
      show-overflow
      size="small"
    >
      <vxe-table-column field="line" sortable title="线路" width="100"></vxe-table-column>
      <vxe-table-column field="license_plate_num" sortable title="车牌号" width="120"></vxe-table-column>
      <vxe-table-column field="total_grade" sortable title="得分" width="120"></vxe-table-column>
      <vxe-table-column field="ranking" sortable title="名次" width="120"></vxe-table-column>
      <vxe-table-column field="reward_punish_text" sortable title="奖励/处罚" width="120"></vxe-table-column>
      <vxe-table-column field="should_reward_punish" sortable title="应奖/惩金额" width="120"></vxe-table-column>
      <vxe-table-column
        :edit-render="{name: 'input'}"
        field="real_reward_punish"
        sortable
        title="实际奖/惩金额"
        width="120"></vxe-table-column>
      <vxe-table-column field="driver" sortable title="司机" width="120"></vxe-table-column>
      <vxe-table-column field="work_day" sortable title="出勤天数" width="120"></vxe-table-column>
      <vxe-table-column field="day_money" sortable title="元/天" width="120"></vxe-table-column>
      <vxe-table-column field="reward_punish_money" sortable title="奖惩金额" width="120"></vxe-table-column>
      <vxe-table-column
        :edit-render="{name: 'input'}"
        field="remark"
        sortable
        title="备注"
        width="120"></vxe-table-column>
    </vxe-table>
  </Card>
</template>
<script>
import {editEleTaskRanks, eleTaskRank, eleTaskRankList} from '../../api/eleTaskSalary'
import XEUtils from 'xe-utils'

export default {
  data() {
    return {
      showAlert: false,
      total: 0,
      showModal: false,
      dataLoading: false,
      listLoading: false,
      sortLoading: false,
      exportBtnDisable: true,
      height: '450',
      searchForm: {
        line: '-1',
        date: '',
        license_plate_num: '',
        sort: '',
        order_sort: '',
        pageNumber: 1, // 当前页数
        pageSize: 10 // 页面大小
      },
      dataForm: {
        date: ''
      },
      data: [],
      lines: [],
      date_text: '',
      allAlign: 'center'
    }
  },
  watch: {
    $route: 'getDataList'
  },
  mounted() {
    this.init()
    const body_h = document.body.clientHeight
    const form_h = document.getElementById('searchForm').offsetHeight
    const row_h = document.getElementById('generate').offsetHeight
    this.height = body_h - form_h - row_h - 200
  },
  methods: {
    changePage(v) {
      this.searchForm.pageNumber = v
      this.getDataList()
    },
    createData() {
      if (!this.dataForm.date) {
        this.$Message.error('请选择生成排名的日期')
        return
      }
      eleTaskRankList(this.dataForm).then(res => {
        if (res.data.result.length == 0) {
          this.dataLoading = true
          eleTaskRank(this.dataForm).then(res => {
            this.dataLoading = false
            if (res.data) {
              if (res.data.result.length == 0) {
                this.$Message.error('请先生成任务工资或当前没有考勤信息')
              } else {
                this.$Message.success('任务工资排名已生成')
                this.getDataList()
              }
            } else {
              this.$Message.error(res.message)
            }
          })
        } else {
          this.$Modal.confirm({
            title: '已生成排名，确认重新生成？',
            loading: true,
            content: '已生成排名，确认重新生成？',
            onOk: () => {
              this.$Modal.remove()
              this.dataLoading = true
              eleTaskRank(this.dataForm).then(res => {
                this.dataLoading = false
                if (res.data) {
                  this.$Message.success('排名已生成')
                  this.getDataList()
                } else {
                  this.$Message.error(res.message)
                }
              })
            }
          })
        }
      })
    },
    dateChange(v) {
      const month = new Date(this.searchForm.date)
      const year = month.getFullYear()
      let start_month =
        month.getMonth() > 9 ? month.getMonth() : '0' + month.getMonth()
      const end_month =
        month.getMonth() + 1 > 9
          ? month.getMonth() + 1
          : '0' + (month.getMonth() + 1)
      let start_year = month.getFullYear()
      if (start_month == '00') {
        start_year = year - 1
        start_month = 12
      }
      const start_time = start_year + '-' + start_month + '-26'
      const end_time = year + '-' + end_month + '-25'
      if (v == 'search') {
        this.date_text = '搜索时间：' + start_time + ' 到 ' + end_time
      } else {
        this.date_text = '生成数据时间：' + start_time + ' 到 ' + end_time
      }
    },
    dateChange(e) {
      this.searchForm.date = e
    },
    edit(row) {
      this.$router.push({
        name: 'editEleSalaryRank',
        params: {
          id: row.id
        }
      })
    },
    //导出
    exportTaskRank() {
      const line = this.searchForm.line
      const license_plate_num = this.searchForm.license_plate_num
      const date = this.searchForm.date

      window.location.href =
        '/api/exportEleTaskRank?line=' +
        line +
        '&license_plate_num=' +
        license_plate_num +
        '&date=' +
        date
    },
    getDataList() {
      this.listLoading = true
      eleTaskRankList(this.searchForm).then(res => {
        this.listLoading = false
        this.data = res.data.result

        this.total = res.data.count
        this.lines = res.data.line
        this.searchForm.date = res.data.date
        if (
          this.searchForm.line ||
          this.searchForm.license_plate_num ||
          this.searchForm.date
        ) {
          this.exportBtnDisable = false
        }
        const month = new Date(this.searchForm.date)
        const year = month.getFullYear()
        let start_month =
          month.getMonth() > 9 ? month.getMonth() : '0' + month.getMonth()
        const end_month =
          month.getMonth() + 1 > 9
            ? month.getMonth() + 1
            : '0' + (month.getMonth() + 1)
        let start_year = month.getFullYear()
        if (start_month == '00') {
          start_year = year - 1
          start_month = 12
        }
        const start_time = start_year + '-' + start_month + '-26'
        const end_time = year + '-' + end_month + '-25'
        this.date_text = '搜索时间为：' + start_time + ' 到 ' + end_time
        this.showAlert = true
      })
    },
    handleReset() {
      this.searchCardForm = {
        line: '-1',
        license_plate_num: '',
        pageNumber: 1,
        pageSize: 10
      }
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
    },
    init() {
      this.getDataList()
    },
    handleSpan({row, $rowIndex, column, data}) {
      const fields = ['line', 'license_plate_num']
      const cellValue = XEUtils.get(row, column.property)
      if (cellValue && fields.includes(column.property)) {
        const prevRow = data[$rowIndex - 1]
        let nextRow = data[$rowIndex + 1]
        if (prevRow && XEUtils.get(prevRow, column.property) === cellValue) {
          return {rowspan: 0, colspan: 0}
        } else {
          let countRowspan = 1
          while (nextRow && XEUtils.get(nextRow, column.property) === cellValue) {
            nextRow = data[++countRowspan + $rowIndex]
          }
          if (countRowspan > 1) {
            return {rowspan: countRowspan, colspan: 1}
          }
        }
      }
    },
    saveEvent() {
      const updateRecords = this.$refs.xTable.getUpdateRecords()
      if (updateRecords.length === 0) {
        this.$message.info('未编辑数据')
      } else {
        editEleTaskRanks(updateRecords).then(res => {
          if (res.data.result) {
            this.$Message.success(res.message)
            this.getDataList()
          } else {
            this.$Message.error(res.message)
          }
        })
      }
    }
  }
}
</script>
<style src="./salaryAccounting.css"></style>
